package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.utils.PayUtils;
import com.itheima.reggie.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetaiLMapper;
    /**
     * 作用： 下单  (本质：把购物车的数据转换为一个Orders 与多个OrderDetail)
     * @param orders  订单的信息（地址id，支付方式，备注）
     * @Param userId  当前的登陆者
     * @return
     */
    @Override
    public Orders submit(Orders orders, Long userId) {
        //A. 获得当前用户id, 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findByUserId(userId);

        //B. 根据当前登录用户id, 查询用户数据
        User user = userMapper.findByUserId(userId);

        //C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());

        //订单的id
        Long orderId = UUIDUtils.getUUIDInOrderId().longValue();
        //声明变量记录总金额
        BigDecimal totalAmount = new BigDecimal("0");
        //D. 遍历所有的购物像， 一个购物项就是一个订单明细， 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(UUIDUtils.getUUIDInOrderId().longValue());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setImage(shoppingCart.getImage());

            //计算每一个购物项的总价
            BigDecimal amount = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber()));
            totalAmount = totalAmount.add(amount);

            orderDetailList.add(orderDetail);
        }
        //E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(0);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(totalAmount);
        orders.setUserName(user.getName());
        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setCheckoutTime(LocalDateTime.now());
        //插入订单
        orderMapper.save(orders);

        //批量插入订单项
        orderDetaiLMapper.saveBatch(orderDetailList);

        //F. 删除当前用户的购物车列表数据
       shoppingCartMapper.clean(userId);

       return orders;
    }

    @Override
    public Page<Orders> userPage(Integer page, Integer pageSize) {

        //设置当前页与页面大小
        PageHelper.startPage(page, pageSize);

        //获取数据
        List<Orders> ordersList = orderMapper.findAll();

        //创建PageInfo
        PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);

        //创建Page
        Page<Orders> ordersPage = new Page<>(ordersList,ordersPageInfo.getTotal(),page,pageSize,ordersPageInfo.getPages());

        return ordersPage;
    }

    @Override
    public Page<Orders> page(Integer page, Integer pageSize,String beginTime,String endTime,Long number) {
        //设置当前页与页面大小
        PageHelper.startPage(page, pageSize);

        //获取数据
        List<Orders> ordersList = orderMapper.findAllByEmpolee(beginTime,endTime,number);

        //创建PageInfo对象
        PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);

        //创建Page对象
        Page<Orders> ordersPage = new Page<>(ordersList,ordersPageInfo.getTotal(),page,pageSize);
        return ordersPage;
    }

    @Override
    public Boolean updateStatus(Map<String,String> map) {

        PayUtils.checkResultCode(map);

        String oid = map.get("out_trade_no");
        orderMapper.updateStatus(Long.parseLong(oid));

        return true;
    }

}
